<?php


namespace App\Service\client;


use App\Common\Res;
use App\Common\StringUtils;
use App\Common\Time;
use App\Constants\ConstCode;
use App\Constants\ErrorCode;
use App\Model\form\MobilePoolTrait;
use App\Model\Task;
use App\Model\TaskMobile;
use App\Model\MobilePool;
use Hyperf\DbConnection\Db;

class taskMobileService
{
    use Res, StringUtils, MobilePoolTrait;

    /**
     *生成任务号码表
     * @param array $params
     * @return array
     */
    public function getTaskMobile(array $params): array
    {
        //先查询任务对应数量号码，放入任务号码表
        Db::beginTransaction();
        try {
            /*获取对应总库条数*/
            $mobilePoolList = MobilePool::where(['status' => ConstCode::USE_STATUS_NO, 'package_id' => $params['package_id']])->get()->toArray();
            $taskMobileCount = TaskMobile::where(['task_id' => $params['id'], 'package_id' => $params['package_id']])->count();
            if (!empty($mobilePoolList) && $taskMobileCount == 0) {
                $numberStr = $this->setNumberStr();
                foreach ($mobilePoolList as $value) {
                    $bookname = $this->getRandomName();
                    $data['mobile'] = $value['mobile'];
                    $data['task_id'] = $params['id'];
                    $data['mobile_pool_id'] = $value['id'];
                    $data['numberStr'] = $numberStr;
                    $data['bookname'] = $bookname;
                    $data['package_id'] = $params['package_id'];
                    $data['userId'] = $this->getRandomUserId();
                    $res = TaskMobile::updateOrCreate(['task_id' => $params['id'], 'mobile' => $value['mobile']], $data);
                    if ($res) {
                        $mobilePoolRes = MobilePool::where(['id' => $value['id'], 'package_id' => $value['package_id']])->first();
                        $mobilePoolRes->status = ConstCode::USE_STATUS_SEND;
                        $mobilePoolRes->save();
                    }
                }
                $task = Task::where(['id' => $params['id']])->first();
                $task->is_working = ConstCode::IS_WORKING;
                $task->save();
                Db::commit();
                return $this->Success('号码发放成功', $numberStr);
            } else {
                Db::commit();
                return $this->Error(ErrorCode::ERROR, '无库存号码或无需发放号码');
            }
        } catch (\Throwable $ex) {
            Db::rollBack();
            return $this->Error(ErrorCode::ERROR, '号码发放失败' . $ex->getMessage());
        }
    }

    /**
     * 给设备发送任务
     * @param $task
     * @param $task_account
     * @return array
     */
    public function sendTaskMobile($task, $task_account): array
    {
        $time = $task['wait_time'] * 60 + rand(60, 120);//固定间隔时间加
        $today_time = Time::today();
        $query = TaskMobile::where(['task_id' => $task['id'], 'account_id' => $task_account['id'], 'status' => ConstCode::USE_STATUS_SEND]);
        $where = function ($query) use ($today_time, $task, $task_account) {
            $query->where('send_time', '>', $today_time['start']);
            $query->where('send_time', '<=', $today_time['end']);
        };
        $count = $query->where($where)->count();
        $max_send_time = $query->max('send_time');
        $map = function ($query) use ($today_time, $task, $task_account) {
            $query->where('task_id', $task['id']);
            $query->where('status', ConstCode::USE_STATUS_NO);
            $query->where('marketUserId', '=', 0);
        };
        $map_1 = function ($query) use ($today_time, $task, $task_account) {
            $query->where('task_id', $task['id']);
            $query->where('status', ConstCode::USE_STATUS_NO);
            $query->where('account_id', $task_account['id']);
        };
        if (!empty($max_send_time)) {
            if (($count <= $task['limit']) && (time() - $max_send_time >= $time)) {
                $sendTask = TaskMobile::where($map_1)->orderBy('id')->first();
                if (empty($sendTask)) {
                    $sendTask = TaskMobile::where($map)->orderBy('id')->first();
                }
                if (!empty($sendTask)) {
                    // $sendTask->send_time = time();
                    // $sendTask->status = ConstCode::USE_STATUS_SEND;
                    $sendTask->account_id = $task_account['id'];
                    $sendTask->save();
                    return $sendTask->toArray();
                }
            }
        } else {
            if ($count <= $task['limit']) {
                $sendTask = TaskMobile::where($map_1)->orderBy('id')->first();
                if (empty($sendTask)) {
                    $sendTask = TaskMobile::where($map)->orderBy('id')->first();
                }
                if (!empty($sendTask)) {
//                    $sendTask->send_time = time();
//                    $sendTask->status = ConstCode::USE_STATUS_SEND;
                    $sendTask->account_id = $task_account['id'];
                    $sendTask->save();
                    return $sendTask->toArray();
                }
            }
        }
        return [];
    }


    /**
     * 给设备发送好友任务
     * @param $task
     * @param $task_account
     * @return array
     */
    public function sendTaskFriendMobile($task, $task_account): array
    {
        $time = $task['wait_time'] * 60;//固定间隔时间
        $today_time = Time::today();
        $query = TaskMobile::where(['task_id' => $task['id'], 'account_id' => $task_account['account_id'], 'status' => ConstCode::USE_STATUS_SEND]);
        $where = function ($query) use ($today_time) {
            $query->where('send_time', '>', $today_time['start']);
            $query->where('send_time', '<=', $today_time['end']);
        };
        $count = $query->where($where)->count();
        $max_send_time = $query->max('send_time');
        $map = function ($query) use ($task, $task_account) {
            $query->where('task_id', $task['id']);
            $query->where('status', 0);
            $query->where('account_id', $task_account['account_id']);
        };
//        Db::beginTransaction();
//        try {
        /*如果已经发送，且收到回调*/
        if (!empty($max_send_time)) {
            if (($count < $task['limit']) && (time() - $max_send_time >= $time)) {
                /*如果已经过了等待时间，查寻是否有没有收到回调的，有则取该条，没有取一条*/
                $sendTask = TaskMobile::where($map)->orderBy('id')->first();
                if (empty($sendTask)) {
                    /*如果没有，就去号码池取一条，并生成一条数据*/
                    $mobileFriend = $this->getMobilePoolByOrder(['status' => 0, 'package_id' => $task['package_id']], 'id');
                    if (!empty($mobileFriend)) {
                        $numberStr = $this->setNumberStr();
                        $bookname = $this->getRandomName();
                        $data['mobile'] = $mobileFriend['mobile'];
                        $data['task_id'] = $task['id'];
                        $data['mobile_pool_id'] = $mobileFriend['id'];
                        $data['numberStr'] = $numberStr;
                        $data['bookname'] = $bookname;
                        $data['package_id'] = $task['package_id'];
                        $data['account_id'] = $task_account['account_id'];
                        $data['userId'] = $this->getRandomUserId();
                        $res = TaskMobile::updateOrCreate(['task_id' => $task['id'], 'mobile' => $mobileFriend['mobile']], $data);
                        if ($res) {
                            $mobileFriend->status = ConstCode::USE_STATUS_SEND;
                            $mobileFriend->save();
                        }
                        $task = Task::where(['id' => $task['id']])->first();
                        $task->is_working = ConstCode::IS_WORKING;
                        $task->save();
                        $data['delay'] = rand(1, 900);//随机时间
                        // Db::commit();
                        return $data;
                    } else {
                        return [];
                    }
                }
                //Db::commit();
                $sendTaskArr = $sendTask->toArray();
                $sendTaskArr['delay'] = rand(1, 900);//随机时间;
                return $sendTaskArr;
            }
        } else {
            /*如果没有发送过数据*/
            if ($count < $task['limit']) {
                /*如果已经过了等待时间，查寻是否有没有收到回调的，有则取该条，没有取一条*/
                $sendTask = TaskMobile::where($map)->orderBy('id')->first();
                if (empty($sendTask)) {
                    /*如果没有，就去号码池取一条，并生成一条数据*/
                    $mobileFriend = $this->getMobilePoolByOrder(['status' => 0, 'package_id' => $task['package_id']], 'id');
                    if (!empty($mobileFriend)) {
                        $numberStr = $this->setNumberStr();
                        $bookname = $this->getRandomName();
                        $data['mobile'] = $mobileFriend['mobile'];
                        $data['task_id'] = $task['id'];
                        $data['mobile_pool_id'] = $mobileFriend['id'];
                        $data['numberStr'] = $numberStr;
                        $data['bookname'] = $bookname;
                        $data['package_id'] = $task['package_id'];
                        $data['account_id'] = $task_account['account_id'];
                        $data['userId'] = $this->getRandomUserId();
                        $res = TaskMobile::updateOrCreate(['task_id' => $task['id'], 'mobile' => $mobileFriend['mobile']], $data);
                        if ($res) {
                            $mobileFriend->status = ConstCode::USE_STATUS_SEND;
                            $mobileFriend->save();
                        }
                        $task = Task::where(['id' => $task['id']])->first();
                        $task->is_working = ConstCode::IS_WORKING;
                        $task->save();
                        $data['delay'] = rand(1, 900);//随机时间;
                        //Db::commit();
                        return $data;
                    } else {
                        return [];
                    }
                }
                // Db::commit();
                $sendTaskArr = $sendTask->toArray();
                $sendTaskArr['delay'] = rand(1, 900);//随机时间;
                return $sendTaskArr;
            }
        }
        //     Db::commit();
        return [];
//        } catch (\Throwable $ex) {
//            Db::rollBack();
//            return [];
//        }
    }


}